import { Component, OnInit } from '@angular/core';
import { NewsService } from '../../service/news.service';
import { Router, ActivatedRoute } from '@angular/router';
import { News } from '../../model/news';
import { ConfigService } from '../../service/config.service';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  parm:string;
  news:News;
  config:any;
  uploadurl:string;
  constructor(
    private newsservice:NewsService,
    private router:Router,
    private routerinfo:ActivatedRoute,
    private configservice:ConfigService
  ) {
    this.news=new News();
    this.parm=this.routerinfo.snapshot.params['id'];
   }

   ngOnInit() {
    if(this.parm=='add'){
     this.news=new News();
     //this.uploadurl="http://localhost:8080/manage/ckeditorUpload";
     this.uploadurl=this.configservice.host +"/manage/ckeditorUpload";
     this.config={
       filebrowserImageUploadUrl:this.uploadurl,
       filebrowserUploadMethod : 'xhr',
       //编辑器图片上传时加入令牌环
       fileTools_requestHeaders : {
       'X-Requested-With': 'XMLHttpRequest',
       'Authorization':localStorage.getItem("token")
          }
         }
     }
    else{
     this.getSingleNews(this.parm);
    }
   }

  goBack(){
    this.router.navigate(['listnews']);
    }

    save(){
      console.dir(this.news);
      if(this.parm=='add'){

        this.addNews();
       }
       else{
         this.updateNews();
       }
    }
  
    addNews(){
      this.newsservice.addNews(this.news).then((flag:boolean)=>{
       if(flag==true){
         this.goBack();
       }
       else{
         alert('保存异常，请刷新后重试');
       }
      })
     }

     updateNews(){
      this.newsservice.updateNews(this.news).then((flag)=>{
       if(flag==true){
         this.goBack();
       }
       else{
         alert('保存异常，请刷新后重试');
       }
      })
    }

    getSingleNews(id:string){
      this.newsservice.getSingleNews(id).then((data:News)=>{
       if(data){
      this.news=data;
       }
       else{
         alert("通讯异常，请刷新后重试");
       }
      })
    }
 



}
